const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
const path = require('path');
require('dotenv').config();
const WebSocketServer = require('./websocket');

const app = express();

// 中间件
app.use(cors());
app.use(morgan('dev'));
app.use(express.json());

// 静态文件服务
app.use('/uploads', express.static(path.join(__dirname, '../uploads')));

// 路由
const indexRouter = require('./routes/index');
const publicRouter = require('./routes/public');  // 新增公共路由
const uploadRouter = require('./routes/upload');

// 注册路由
app.use('/api/upload', uploadRouter);  // 文件上传接口
app.use('/api/public', publicRouter);  // 公共接口
app.use('/api', indexRouter);          // 需要token验证的接口

// 基础路由
app.get('/', (req, res) => {
  res.json({ message: 'Welcome to the API' });
});

// 错误处理
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({
    code: ResponseCode.SERVER_ERROR,
    message: '服务器内部错误'
  });
});

const PORT = process.env.PORT || 3000;
const server = app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

// 初始化WebSocket服务
const wss = new WebSocketServer(server);
global.wss = wss; 